/**
 * 分类
 */
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { StoreName } from '../store-enum.d'
import { categoryAPI } from '@/api/home'
import { type Category } from '@/api/home/types.d'

/** 防止刷新数据还没获取到，导航栏出现空白 */
const initialCateList = [
  {
    id: '',
    name: '居家',
    picture: '',
    children: [],
    goods: []
  },
  {
    id: '',
    name: '美食',
    picture: '',
    children: [],
    goods: []
  },
  {
    id: '',
    name: '服饰',
    picture: '',
    children: [],
    goods: []
  },
  {
    id: '',
    name: '母婴',
    picture: '',
    children: [],
    goods: []
  },
  {
    id: '',
    name: '个护',
    picture: '',
    children: [],
    goods: []
  },
  {
    id: '',
    name: '严选',
    picture: '',
    children: [],
    goods: []
  },
  {
    id: '',
    name: '数码',
    picture: '',
    children: [],
    goods: []
  },
  {
    id: '',
    name: '运动',
    picture: '',
    children: [],
    goods: []
  },
  {
    id: '',
    name: '杂项',
    picture: '',
    children: [],
    goods: []
  }
]

export const useCategoryStore = defineStore(
  StoreName.CATEGORY,
  () => {
    /** 分类列表 */
    const categoryList = ref<Category[]>(initialCateList)

    /** 获取全部分类列表 */
    const getCategoryList = async (): Promise<void> => {
      try {
        const result = await categoryAPI()
        result.forEach((category) => (category.open = false))
        categoryList.value = result
      } catch (error) {
        console.log(error)
      }
    }

    /**
     * 显示二级分类列表
     * @param {Category} cate
     */
    const showSub = (cate: Category): void => {
      const category = categoryList.value.find(
        (category) => cate.id === category.id
      )
      category!.open = true
    }

    /**
     * 隐藏二级分类列表
     * @param {Category} cate
     */
    const hideSub = (cate: Category): void => {
      const category = categoryList.value.find(
        (category) => cate.id === category.id
      )
      category!.open = false
    }

    return {
      categoryList,
      getCategoryList,
      showSub,
      hideSub
    }
  } /** 持久化存储，默认存储到localstorage */,
  {
    persist: {
      key: 'category-store' // 存储到localstorage中的key名称
    }
  }
)
